package com.lazy.service.impl;


import com.lazy.constant.MessageConstant;
import com.lazy.context.BaseContext;
import com.lazy.dto.StudentDTO;
import com.lazy.dto.StudentLoginDTO;
import com.lazy.entity.Student;
import com.lazy.mapper.StudentMapper;
import com.lazy.service.StudentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    /**
     * 登录校验
     * @param studentLoginDTO
     * @return
     */
    @Override
    public Student login(StudentLoginDTO studentLoginDTO) {
        String username = studentLoginDTO.getUsername();
        String password = studentLoginDTO.getPassword();
        //1、根据用户名查询数据库中的数据
        Student student = studentMapper.getByUsername(username);
        //2、处理各种异常情况（用户名不存在、密码不对）
        if (student == null){
            // 账号不存在
            throw new RuntimeException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        if (!student.getPassword().equals(password)){
            //密码错误
            throw new RuntimeException(MessageConstant.PASSWORD_ERROR);
        }
        //3、返回实体对象
        return student;
    }

    /**
     * 注册
     * @param studentDTO
     */
    @Override
    public void register(StudentDTO studentDTO) {
        Student student = new Student();
        BeanUtils.copyProperties(studentDTO,student);

        // 设置创建时间和修改时间
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());

        // 向数据库插入数据
        studentMapper.insert(student);
    }

    /**
     * 根据id查询学生信息
     * @return
     */
    @Override
    public Student selectById() {
        Student student = new Student();
        Long id = BaseContext.getCurrentId();
        student.setId(id);
        return studentMapper.selectById(student.getId());
    }


}
